var _special_id = 609;
var _mob_key = '';

function zform_obj() {
    this.config = null;
    this.attr = [];
    this.reAll = [];
    this.postUrl = window.location.origin + '/special/data?id=609';
    this.errors = {};
    this.verifyData = {
        phone: {
            test: /\d{11}/,
            msg: '手机号',
        },
        email: {
            test: /\S+@\S+\.\S+/,
            msg: '电子邮箱',
        },
        number: {
            test: /\D+/,
            msg: "数字",
        },
        date: {
            test: /\d{4}[-|\\]\d{2}[-|\\]\d{2}(\ \d{2}[:]\d{2}[:]\d{2})?(\ \d{2}[:]\d{2})?/,
            msg: "日期",
        }
    };
}

zform_obj.prototype.getHtml = function () {
    var html = "";
    for(var i in this.attr){
        let data = this.attr[i];
        console.log("bugversion",data);
        var input = "";
        switch (data.type+"") {
            case "1":
                input = `<input name='${data.pinyin}' placeholder='${data.placeholder}' type='text' />`;
                break;
            case "2":
                input = `<textarea  name='${data.pinyin}' placeholder='${data.placeholder}'></textarea>`;
                break;
            case "3":
                var child = "";
                for(var i in data.child){
                    let res = data.child[i];
                    child += `<option value='${res.id}'>${res.name}</option>`;
                }
                input =
                    `<select name='${data.pinyin}'>
                        <option value="0">${data.placeholder}</option>
                        ${child}
                    </select>`;
                break;
            case "4":
                var child = "";
                for (var i in data.child) {
                    let res = data.child[i];
                    let checked = "";
                    if (i == 0) {
                         checked = "checked='checked'";
                    }
                    child += `<div>
                                <input type="radio" value='${res.id}' id='${res.id}' name='${data.pinyin}' ${checked} />
                                <label for='${res.id}'>${res.name}</label>
                            </div>`;
                }
                input = `<div> ${child} </div>`;
                break;
            case "5":
                var child = "";
                for (var i in data.child) {
                    let res = data.child[i];
                    child += `<div>
                                <input type="checkbox" value="${res.id}" id="${res.id}" name='${data.pinyin}' />
                                <label for="${res.id}"> ${res.name} </label>
                            </div>`;
                }
                input = `<div> ${child} </div>`
                break;
            default:
                break;
        }
        var label = `<span>${data.name}：</span>`;
        html += `<div>${label}${input}</div>`;
    }
    return `<form>${html}</form>`;
}

zform_obj.prototype.getPostData = function() {
    var data = $('form').serializeArray();
    var post = {};
    for(var i in this.attr){
        post[i] = '';
    }
    for (var i in data) {
        if (!post[data[i].name]) {
            post[data[i].name] = data[i].value;
        } else {
            post[data[i].name] += "," + data[i].value;
        }
    }
    return post;
}

zform_obj.prototype.verifyFunc = function(data, func) {
    this.errors = {};
    for (var i in this.attr) {
        var obj = this.attr[i];
        var isError = false;
        if (obj['func']) {
            obj.func(i, data[i],obj.name);
            continue;
        }
        if (obj.properties['required'] == 1 && !data[i]) {
            if ( [5].indexOf(obj.type) != -1 ) {
                this.errors[i] = "请选择" + obj.name;
            } else {
                this.errors[i] = "请输入" + obj.name;
            }
            isError = true;
        }
        if (!isNaN(obj.properties['length']) && data[i].length > obj.properties['length']) {
            if (!isError) {
                this.errors[i] = obj.name + "超出长度限制";
            }
        }
        if (obj.properties['validation'] && this.verifyData[i] && !this.verifyData[i].test.test(data[i])) {
            if (!isError) {
                this.errors[i] = obj.name + "格式错误";
            }
        }
        if (obj.properties['scope'] && data[i] && data[i].split(',').length) {
            if (!(data[i].split(',').length >= obj.properties['scope'][0] && data[i].split(',').length <= obj.properties['scope'][1])) {
                if (!isError) {
                    this.errors[i] = obj.name + `选择数量在${obj.properties['scope'][0]} - ${obj.properties['scope'][1]}之间`;
                }
            }
        }
    }
    var isForSub = true;
    for (var i in this.errors) {
        isForSub = false;
    }
    if (isForSub) {
        this.submit(data, func);
    } else {
        console.log('errors',this.errors);
    }
    return isForSub;
}

zform_obj.prototype.getError = function() {
    var sort = {};
    for(var i in this.attr){
        sort[
            this.attr[i]['sort']
        ] = i;
    }
    res = [];
    for(var i in sort){
        res.unshift(sort[i]);
    }
    for(var i in res){
        if (this.errors[res[i]]) {
            return this.errors[res[i]];
        }
    }
    return false;
}

zform_obj.prototype.submit = function(data, func) {
    var _this = this;
    $.post(this.postUrl, data, function(res) {
        if (func) {
            if (func(res)) {
                window.location.href = _this.config.url;
            }
        }
    }, 'json');
}

function zwx() {
    this.special = {"id":609,"cate_id":0,"total":202,"base":10,"user_id":340,"recommend":0,"is_form":0,"form_id":0,"name":"明都汽车十一","pinyin":"","img":"https:\/\/pic.haoshikou.net\/FoJWc-Wd1EGpMW2veNKcbrPzSf64.png","status":1,"wx_share":0,"app_share":0,"share_title":"明都汽车【国庆云车展】10万元汽油订车抽  1千元红包订车送！","share_img":"https:\/\/pic.haoshikou.net\/FoJWc-Wd1EGpMW2veNKcbrPzSf64.png","share_desc":"国庆购车去哪里？\r\n就到明都云车展！\r\n（10月1日-5日）","host":"","is_open":1,"rmb":"0.00","original_rmb":0,"type":1,"last_user_id":340,"created_at":1727056574,"updated_at":1727247198,"is_sms":0,"phone":""};
    if (this.special.status!=1) {
        window.location.href = "/404/index.html";
        return;
    }
    this.shareMsg = {
        title: this.special.share_title,
        desc: this.special.share_desc,
        link: this.special.host ? this.special.host : window.location.origin.replace(/:\d+/,'') + window.location.pathname,
        imgUrl: this.special.share_img,
        type: '',
        dataUrl: '',
        success: function() {},
        cancel: function() {}
    }
    var index = navigator.userAgent.toLowerCase().indexOf('qianfan');
    if (index != -1) {
        QFH5.setShareInfo(this.shareMsg.title, this.shareMsg.image, this.shareMsg.desc, this.shareMsg.link, function(state, data) {
        });
    }
    var _this = this;
    $.get(window.location.origin + '/special/js-wx-token', {
        url: window.location.href
    }, function(res) {
        var data = res.data;
        data.jsApiList = [
            "updateAppMessageShareData", "onMenuShareTimeline", "onMenuShareAppMessage",
            "startRecord","stopRecord","playVoice","uploadVoice"
        ];
        wx.config(data);
    }, 'json');
}
zwx.prototype.share = function(msg) {
    for (var i in msg) {
        this.shareMsg[i] = msg[i];
    }
    wx.onMenuShareTimeline(this.shareMsg);
    wx.onMenuShareAppMessage(this.shareMsg);
    wx.updateAppMessageShareData(this.shareMsg)
}
var wxk = new zwx();
window.wx && wx.ready(function() {
    if (getCookie('special_' + wxk.special.id) != null) {
        var link = addParam(wxk.shareMsg.link, 'share', getCookie('special_' + wxk.special.id));
        wxk.share({
            link: link
        });
    }
    wxk.share({});
});
// 统计
function setCookie(name, value) {
    var exp = new Date();
    exp.setDate(exp.getDate() + 1);
    exp.setSeconds(0);
    exp.setMinutes(0);
    exp.setHours(0);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) return unescape(arr[2]);
    else return null;
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
};

function addParam(url, paramKey, paramVal) {
    var andStr = "?";
    var beforeparam = url.indexOf("?");
    if (beforeparam != -1) {
        andStr = "&";
    }
    return url + andStr + paramKey + "=" + encodeURIComponent(paramVal);
}

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}
var _total_src = '/special/total?id=' + _special_id;
if (GetQueryString('share') != null) {
    // 来源于分享
    _total_src += '&share=' + GetQueryString('share');
}
if (getCookie('special_' + _special_id) == null) {
    // 本日首次访问
    var uuid = uuid();
    setCookie('special_' + _special_id, uuid);
    _total_src += '&frist=' + uuid;
}
var script = document.createElement("script");
script.type = "text/javascript";
script.src = _total_src;
document.body.appendChild(script);
